<template>
    <el-row>
        <!-- 头部 -->
        <el-col :span="24">
            <el-card shadow="hover">
                <el-breadcrumb :separator-icon="ArrowRightBold">
                    <el-breadcrumb-item :to="{ path: '/admin_index' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>开奖管理</el-breadcrumb-item>
                    <el-breadcrumb-item>{{ gameConfig.name }}</el-breadcrumb-item>
                </el-breadcrumb>
            </el-card>
        </el-col>
        <div style="padding: 5px;"></div>
        <!-- 内容区域 -->
        <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div style="display: flex;justify-content: space-between">
                  <div style="display: flex; align-items: center;">
                    <el-input style="width: 260px;" v-model="inputval" placeholder="请输入开奖期号" />
                    <div style="padding: 5px;"></div>
                    <el-button type="primary" :icon="Search" @click="inputSearch()">搜索</el-button>
                    <div style="width: 50px;"></div>
                    <el-button type="primary" :icon="Search" @click="show_yskj()">预设开奖</el-button>
                  </div>
                  <div>
                    <span style="margin-left:10px;">只显示进行和预设</span>
                    <el-tooltip :content="page.is_ys == 1 ? '是' : '否'" placement="top">
                      <el-switch :model-value="page.is_ys" :active-value="1" :inactive-value="0"  @change="changeIsYs"></el-switch>
                    </el-tooltip>
                  </div>
                </div>
              </template>

                <!-- 表格 -->
                <el-table :data="tableData.list" :border="true" style="width: 100%">
                    <el-table-column prop="id" label="序号" width="100" >
                      <template #default="scope">
                        <div style="font-weight: bold;">{{ scope.row.id }}</div>
                      </template>
                    </el-table-column>

                    <el-table-column label="游戏类型">
                        <template #default="scope">
                            <el-tag>{{ gameConfig.name }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="issue" label="开奖期号" >
                      <template #default="scope">
                        <div style="font-weight: bold;">{{ scope.row.issue }}</div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="number" label="开奖号码" >
                      <template #default="scope">
                        <div style="font-size: 18px; text-align: center; font-weight: bold;">{{ scope.row.number }}</div>
                        <div style="display: flex;justify-content: center">
                          <div class="tag_box" v-for="(v,i) in scope.row.bet_name" :key="i" >
                            <el-tag  type="danger" v-if="['大','大单','大双','单'].includes(v)" style="font-weight: bold;">{{v}}</el-tag>
                            <el-tag  type="success" v-else style="font-weight: bold;">{{v}}</el-tag>
                          </div>

                        </div>
                      </template>
                    </el-table-column>

                  <el-table-column prop="time" label="系统开奖时间">
                    <template #default="scope">
                      <div v-if="scope.row.status==1" style="font-weight: bold;">
                        <Countdown :seconds="scope.row.end_time" @finish="handleFinish"/>
                      </div>
                      <div v-else style="font-weight: bold;">
                        {{scope.row.time}}
                      </div>
                    </template>
                  </el-table-column>
                    <el-table-column prop="create_time" label="创建时间" >
                      <template #default="scope">
                        <div style="font-weight: bold;">{{ scope.row.create_time }}</div>
                      </template>
                    </el-table-column>

                    <el-table-column label="开奖状态" width="200">
                        <template #default="scope">
                            <el-tag v-if="scope.row.status == 1" type="danger" plain style="font-weight: bold;">进行中</el-tag>
                            <el-tag v-if="scope.row.status == 2" type="success" plain style="font-weight: bold;">已开奖</el-tag>
                            <el-tag v-if="scope.row.status == 3" type="info" plain style="font-weight: bold;">预设中</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="订单操作" width="190">
                        <template #default="scope">
                            <el-button type="success" @click="show_edit(scope.row)" v-if="scope.row.status != 2">修改</el-button>
                            <el-button type="primary" @click="manual_lottery(scope.row)">手动开奖</el-button>
                        </template>
                    </el-table-column>

                </el-table>
                <!-- 分页 -->

                <div style="padding: 10px;"></div>
                <el-pagination small background v-model:currentPage="page.pagenum" v-model:page-size="page.pagesize"
                    :page-sizes="[20, 50]" :small="small" :background="background" layout="total, prev, pager, next, jumper"
                    :total="page.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

            </el-card>
        </el-col>
    </el-row>

    <!-- 菜单权限管理 -->
    <el-dialog v-model="showDialog" title="手动开奖" center width="50%" :destroy-on-close="true">
        <el-form label-width="80px">
            <el-form-item label="开奖期号">
                <el-input v-model="formData.issue" :disabled="Boolean(formData.issue)" />
            </el-form-item>
            <el-form-item label="开奖号码">
              <div class="number_list">
                <el-select   popper-class="custom-select-dropdown"
                    style="width: 60px;padding:0 10px"
                    v-model="formData.numberArr[0]"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词">
                  <el-option
                      v-for="item in numberArr"
                      :label="item"
                      :value="item"
                      :key="item"
                  >
                  </el-option>
                </el-select>
                <el-select   popper-class="custom-select-dropdown"
                    v-model="formData.numberArr[1]"
                    style="width: 60px;padding:0 10px"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词">
                  <el-option
                      v-for="item in numberArr"
                      :label="item"
                      :value="item"
                      :key="item"
                  >
                  </el-option>
                </el-select>
                <el-select   popper-class="custom-select-dropdown"
                    v-model="formData.numberArr[2]"
                    style="width: 60px;padding:0 10px"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词">
                  <el-option
                      v-for="item in numberArr"
                      :label="item"
                      :value="item"
                      :key="item"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="formSubmit()">确定手动开奖</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="showYskj" title="预设开奖" center width="30%" :destroy-on-close="true">
        <el-form label-width="80px">
            <el-form-item label="预设期数">
                <el-input type="number" v-model="yskjData.num" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="yskjSubmit()" :disabled="isPost">确定预设开奖</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="showEdit" title="修改" center width="500" :destroy-on-close="true">
        <el-form label-width="80px">
            <el-form-item label="号码">
				<div class="number_list">
              <el-select   popper-class="custom-select-dropdown"
                  style="width: 60px;padding:0 10px"
                  v-model="editData.num1"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词">
                <el-option
                    v-for="item in numberArr"
                    :label="item"
                    :value="item"
                    :key="item"
                >
                </el-option>
              </el-select>
              <el-select   popper-class="custom-select-dropdown"
                  v-model="editData.num2"
                  style="width: 60px;padding:0 10px"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词">
                <el-option
                    v-for="item in numberArr"
                    :label="item"
                    :value="item"
                    :key="item"
                >
                </el-option>
              </el-select>
              <el-select   popper-class="custom-select-dropdown"
                  v-model="editData.num3"
                  style="width: 60px;padding:0 10px"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词">
                <el-option
                    v-for="item in numberArr"
                    :label="item"
                    :value="item"
                    :key="item"
                >
                </el-option>
              </el-select>
				</div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" :disabled="editData.num1==null||editData.num2==null||editData.num3==null" @click="editSubmit()">确定修改</el-button>
        </template>
    </el-dialog>
	
</template>

<script setup>

import { ref, reactive, onMounted, computed, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { request_post } from '@/common/axios/request.js'
import { success, error } from '@/common/tool/message.js'
import { ArrowRightBold, Search } from '@element-plus/icons-vue'
import Countdown from '@/components/Countdown.vue';

// 获取路由和路由器实例
const route = useRoute();
const router = useRouter();

// 从查询参数中获取gameType
const gameType = ref(route.query.game || 'xinaozhou');

// 监听查询参数变化

watch(() => router.currentRoute.value.query.game, (newValue, oldValue) => {
  if (newValue && newValue !== oldValue) {
    gameType.value = newValue || 'xinaozhou';
  }
});
const type = ref("");
// 监听gameType变化
watch(gameType, (newValue) => {
  // 更新页面类型
  page.type = gameConfig.value.type;
  // 更新localStorage状态
  page.is_ys = Number(localStorage.getItem(gameConfig.value.localStorageKey)) || 0;
  // 重新加载数据
  loadIssueData();
  // 更新yskjData和editData的type
  type.value = yskjData.type = newValue === 'xinaozhou' ? 'aozhou' : 
                 newValue === 'aomen' ? 'xinjiapo' : 
                 newValue === 'xianggang' ? 'aomenjisu' : 
                 newValue === 'yazhou' ? 'yazhou' :
                 newValue === 'eluosi' ? 'eluosi' :
                 newValue === 'xinjiapo' ? 'xinjiapo28' : 
                 newValue === 'ouzhou' ? 'ouzhou' :
                 newValue === 'aozhou28' ? 'aozhou28' :
                 newValue === 'moxige' ? 'moxige' :
                 newValue === 'taiwan' ? 'taiwan' :
                 newValue === 'jianada' ? 'jianada' :
                 newValue === 'agenting' ? 'agenting' :
                 newValue === 'helan' ? 'helan' :'xinjiapo28';

  type.value = editData.type = newValue === 'xinaozhou' ? 'aozhou' : 
                 newValue === 'aomen' ? 'xinjiapo' : 
                 newValue === 'xianggang' ? 'aomenjisu' : 
                 newValue === 'yazhou' ? 'yazhou' :
                 newValue === 'eluosi' ? 'eluosi' :
                 newValue === 'xinjiapo' ? 'xinjiapo28' : 
                 newValue === 'ouzhou' ? 'ouzhou' : 
                 newValue === 'aozhou28' ? 'aozhou28' :
                 newValue === 'moxige' ? 'moxige' :
                 newValue === 'taiwan' ? 'taiwan' :
                 newValue === 'jianada' ? 'jianada' :
                 newValue === 'agenting' ? 'agenting' :
                 newValue === 'helan' ? 'helan' :'xinjiapo28';
});

// 游戏配置映射表
const gameConfigs = {
  xinaozhou: {
    name: '新澳门28',
    typeName: 'aozhou',
    api: {
      list: '/admin_aozhou_issue',
      manual: '/admin_aozhou_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 1,
    
    localStorageKey: 'is_azs_ys'
  },
  aomen: {
    name: '澳门28',
    typeName: 'xinjiapo',
    api: {
      list: '/admin_xinjiapo_issue',
      manual: '/admin_xinjiapo_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 2,
    localStorageKey: 'is_am_ys'
  },
  xianggang: {
    name: '香港28',
    typeName: 'aomenjisu',
    api: {
      list: '/admin_aomenjisu_issue',
      manual: '/admin_aomenjisu_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 3,
    localStorageKey: 'is_amjs_ys'
  },
  yazhou: {
    name: '亚洲28',
    typeName: 'yazhou',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 5,
    localStorageKey: 'is_yz_ys'
  },
  eluosi: {
    name: '俄罗斯28',
    typeName: 'eluosi',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 6,
    localStorageKey: 'is_els_ys'
  },
  xinjiapo: {
    name: '新加坡28',
    typeName: 'xinjiapo28',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 7,
    localStorageKey: 'is_xjp_ys'
  },
  ouzhou: {
    name: '欧洲28',
    typeName: 'ouzhou',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 8,
    localStorageKey: 'is_oz_ys'
  },
  aozhou28: {
    name: '澳洲28',
    typeName: 'aozhou28',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 9,
    localStorageKey: 'is_az_ys'
  },
  moxige: {
    name: '墨西哥28',
    typeName: 'moxige',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 10,
    localStorageKey: 'is_mxg_ys'
  },
  taiwan: {
    name: '台湾28',
    typeName: 'taiwan',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 11,
    localStorageKey: 'is_tw_ys'
  },
  jianada: {
     name: '加拿大28(自开)',
     typeName: 'jianada28',
     api: {
       list: '/admin_kl28_issue',
       manual: '/admin_kl28_manual_issue',
       edit: '/admin_issue_edit',
       yskj: '/admin_yskj'
     },
     type: 12,
     localStorageKey: 'is_jnd_ys'
   },
  agenting: {
    name: '阿根廷28',
    typeName: 'agenting',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 13,
    localStorageKey: 'is_agt_ys'
  },
  helan: {
    name: '荷兰28',
    typeName: 'helan',
    api: {
      list: '/admin_kl28_issue',
      manual: '/admin_kl28_manual_issue',
      edit: '/admin_issue_edit',
      yskj: '/admin_yskj'
    },
    type: 14,
    localStorageKey: 'is_hl_ys'
  }
};

// 当前游戏配置
const gameConfig = computed(() => gameConfigs[gameType.value] || gameConfigs.xinaozhou);

function handleFinish(){
  setTimeout(()=>{loadIssueData()}, 1000)
}

const showDialog = ref(false)
const tableData = reactive({ list: [] })
const numberArr = ref([0,1,2,3,4,5,6,7,8,9])
const formData = reactive({
    issue: '',
    type: gameConfig.value.type,
    numberArr: [0,0,0],
})
console.log(formData,'formData');
onMounted(() => {
  page.is_ys = Number(localStorage.getItem(gameConfig.value.localStorageKey)) || 0;
  page.type = gameConfig.value.type;
  loadIssueData();
})

const showYskj = ref(false)
const yskjData = reactive({
    type: gameConfig.value.typeName,
    num: 1
})
function show_yskj(item) {
    showYskj.value = true
}
const isPost = ref(false)
function yskjSubmit() {
  if(yskjData.num >= 20) {
    return error('单次预设不得超过20期')
  }
  if (isPost.value) return
  isPost.value = true
    request_post(gameConfig.value.api.yskj, yskjData).then((res) => {
        if (res.data.code == 200) {
            showYskj.value = false
			page.issue = ''
			page.pagenum = 1
			page.pagesize = 18
			page.total = 0
          isPost.value = false
			loadIssueData()
            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })
}

const showEdit = ref(false)
const editData = reactive({
  type: gameConfig.value.typeName,
	id: '',
    num1: 0,
    num2: 0,
    num3: 0,
})
function show_edit(item) {
    showEdit.value = true
	editData.id = item.id
	let number = []
	if(item.number){
		number = item.number.split(",");
	}
	editData.num1 = parseInt(number[0]) || 0
	editData.num2 = parseInt(number[1]) || 0
	editData.num3 = parseInt(number[2]) || 0
}
console.log(gameConfig,'gameConfig');
function editSubmit() {
    request_post(gameConfig.value.api.edit, editData).then((res) => {
        if (res.data.code == 200) {
            showEdit.value = false
			page.issue = ''
			page.pagenum = 1
			page.pagesize = 18
			page.total = 0
			loadIssueData()
            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })
}

function manual_lottery(item) {
    showDialog.value = true
    formData.issue = item.issue
    let number = []
    if(item.number){
      number = item.number.split(",");
    }
    formData.numberArr[0] = parseInt(number[0]) || 0
    formData.numberArr[1] = parseInt(number[1]) || 0
    formData.numberArr[2] = parseInt(number[2]) || 0
}

function formSubmit() {
  formData.number = formData.numberArr.toString()
  formData.type = gameConfig.value.type;
    request_post(gameConfig.value.api.manual, formData).then((res) => {
        if (res.data.code == 200) {
            showDialog.value = false
          page.pagenum = 1
          loadIssueData()
            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })
}

// 搜索 
const inputval = ref('')
function inputSearch() {
    if (inputval.value == '') {
        return error('请输入开奖期号')
    }
    page.issue = inputval.value
    loadIssueData()
}

// 获取用户列表
function loadIssueData() {
    request_post(gameConfig.value.api.list, page).then((res) => {
        if (res.data.code == 200) {
            tableData.list = res.data.data.data
            page.total = res.data.data.total
        } else {
            return error(res.data.msg)
        }
    })
}

const page = reactive({
    issue: '',
    type: gameConfig.value.type,
    pagenum: 1,
    pagesize: 18,
    total: 0,
    is_ys: 0,
})
function changeIsYs(e){
  localStorage.setItem(gameConfig.value.localStorageKey, e)
  page.is_ys = e
  loadIssueData()
}
function handleSizeChange(val) {
    page.pagenum = val
    loadIssueData()
}
function handleCurrentChange(val) {
    page.pagenum = val
    loadIssueData()
}

// 页面可见性变化监听
function handleVisibilityChange() {
  if (document.visibilityState === 'visible') {
    loadIssueData();
  }
}

// 添加事件监听
onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 移除事件监听
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

</script>

<style>
	.number_list{
		display: flex;
		align-items: center;
	}
	.number_list .el-input-number{
		width: 100px;
		margin-right: 15px;
	}
  .tag_box{
    margin:0 2px;
  }
</style>